package com.example.wallpaper.tools;


import android.util.Log;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**封装http请求*/
public class HttpUtil {

    private static final String TAG = "HttpUtil";

    private OkHttpClient mClient;

    public HttpUtil(){
        mClient = new OkHttpClient.Builder()
                .sslSocketFactory(createSSLSocketFactory(),new MyTrustManager())
                .build();

    }

    //响应JSON数据
    public String sendRequest(String url){
        String json = null;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            json = response.body().string();
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    //响应byte[]数据
    public byte[] sendRequestByByteArray(String url){
        byte[] bytes = null;
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            bytes = response.body().bytes();
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        return bytes;
    }


    /**创建SSL工厂，用于绕过某些https地址证书不一致的问题*/
    private SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }

        return ssfFactory;
    }

    /**实现X509TrustManager接口，自定义校验器，用于绕过某些https地址证书不一致的问题*/
    private static class MyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
}
